{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 线性回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#产生原始数据\n",
    "k = 3\n",
    "b = 4\n",
    "def f(x):\n",
    "    return k * x + b\n",
    "n = 100 \n",
    "X = np.linspace(1,100,n)\n",
    "Y = f(X)\n",
    "plt.plot(X,Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#手动添加误差\n",
    "D = np.random.normal(0,3,n)\n",
    "Y += D\n",
    "plt.plot(X,Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设定初始的K和B\n",
    "K = torch.normal(0,1,size(1,1),requires_grad=True)\n",
    "B = torch.normal(0,1,size(1,1),requires_grad=True)\n",
    "#数据处理\n",
    "X = torch.tensor(X)\n",
    "Y = torch.tensor(Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义模型\n",
    "def model(x,k,b):\n",
    "    return k * x + b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义损失函数\n",
    "def squred_loss(y_hat,y)\n",
    "    return (y_hat - y) ** 2 / 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义学习率\n",
    "learn_rate = 0.01\n",
    "\n",
    "for x,y in zip(X,Y):\n",
    "    l = squred_loss(model(x,K,B),y)\n",
    "    l.sum().backward()\n",
    "    with torch.no_grad():\n",
    "        K -= K.grad * learn_rate\n",
    "        B -= B.grad * learn_rate\n",
    "        K.grad.zero_()\n",
    "        B.grad.zero_()\n",
    "    print(K,B)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "d0l",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
